package domain.DAO;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.persistence.criteria.Order;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.Restrictions;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.HibernateTemplate;

import domain.Contact;
import domain.ContactGroup;
import domain.interfaces.IDAOCrud;
import domain.interfaces.IdObject;

import util.HibernateUtil;

public abstract class DAOCrud<T extends IdObject> implements IDAOCrud<T> {

	protected HibernateTemplate hibernateTemplate;

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.hibernateTemplate = new HibernateTemplate(sessionFactory);
	}

	private static final long serialVersionUID = 1L;

	protected Class<T> entityClass;

	public DAOCrud(Class<T> entityClass) {
		this.entityClass = entityClass;
	}

	public void create(T entity) {
		hibernateTemplate.save(entity);
	}

	@SuppressWarnings("unchecked")
	public Set<T> findAll() {
		hibernateTemplate.setCacheQueries(true);
		List<T> all = hibernateTemplate.findByCriteria(DetachedCriteria
				.forClass(this.entityClass));
		hibernateTemplate.setCacheQueries(false);
		return new HashSet<T>(all);
	}

	@SuppressWarnings("unchecked")
	public T find(long id) {
		hibernateTemplate.setCacheQueries(true);
		DetachedCriteria query = DetachedCriteria.forClass(this.entityClass)
				.add(Restrictions.idEq(id));
		hibernateTemplate.setCacheQueries(false);
		return (T) hibernateTemplate.findByCriteria(query).get(0);
		
	}

	public void delete(T entity) {
		hibernateTemplate.delete(entity);
	}

	public void update(T entity) {
		hibernateTemplate.update(entity);
	}
}
